<template>
	<div class="d1">
		<!-- 面包屑导航提示 -->
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 中间区域内容 -->
		<el-card>
			<!-- 搜索框 -->
			<el-form label-width="80px" style="display: inline-block;">
				<el-form-item label="用户名称" prop="name" style="display: inline-block; margin-left: -10px;">
					<el-input placeholder="用户名称" v-model="queryInfo.name" style="width: 240px;">
					</el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="name"
					style="display: inline-block; margin-left: -20px; margin-right: 5px;">
					<el-input placeholder="手机号" v-model="queryInfo.phone" style="width: 240px;">
					</el-input>
				</el-form-item>
				<el-form-item label="注册时间" style="display: inline-block; float: right;">
					<el-date-picker v-model="queryInfo.createtime" type="datetimerange" value-format="yyyy-MM-dd HH:mm" range-separator="至" start-placeholder="开始日期"
						end-placeholder="结束日期">
					</el-date-picker>
				</el-form-item>
			</el-form>
			<el-button type="primary" @click="selectUsers">筛选</el-button>
			<el-button type="primary" @click="selectReset">重置</el-button>
			<el-button type="primary" class="b1" @click="addUserdialogFormVisible=true">新增用户</el-button>
			<!-- 表格数据 -->
			<el-table :data="userList" border style="width: 100%;margin-bottom: 10px;">
				<el-table-column prop="id" label="用户ID">
				</el-table-column>
				<el-table-column prop="name" label="用户姓名">
				</el-table-column>
				<el-table-column prop="phone" label="手机号">
				</el-table-column>
				<el-table-column prop="createTime" label="注册时间">
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-tooltip class="item" effect="dark" content="修改" placement="top">
							<el-button type="primary" icon="el-icon-edit" @click="selectUserById(scope.row.id)"
								size="small">
							</el-button>
						</el-tooltip>
						<el-tooltip class="item" effect="dark" content="删除" placement="top">
							<el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row.id)" size="small">
							</el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
			<div class="block">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="queryInfo.pageNum" :page-sizes="[3,4,5]" :page-size="queryInfo.pageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="queryInfo.total">
				</el-pagination>
				<el-dialog title="添加用户" :visible.sync="addUserdialogFormVisible" @close="addReset"
					style="margin-top: -80px;">
					<el-form :model="addUser" :rules="addRule" ref="adduserref">
						<el-form-item label="账号" :label-width="formLabelWidth" prop="username">
							<el-input v-model="addUser.username" autocomplete="off" class="add" size="small"></el-input>
						</el-form-item>
						<el-form-item label="密码" :label-width="formLabelWidth" prop="password">
							<el-input v-model="addUser.password" autocomplete="off" class="add" size="small"></el-input>
						</el-form-item>
						<el-form-item label="真实姓名" :label-width="formLabelWidth" prop="name">
							<el-input v-model="addUser.name" autocomplete="off" class="add" size="small"></el-input>
						</el-form-item>
						<el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
							<el-input v-model="addUser.phone" autocomplete="off" class="add" @blur="selectUserByPhone"
								size="small"></el-input>
						</el-form-item>
						<el-form-item label="地址" :label-width="formLabelWidth" prop="address">
							<el-cascader v-model="addUser.address" :options="cityData" class="add" size="small">
							</el-cascader>
						</el-form-item>
						<el-form-item label="头像" :label-width="formLabelWidth" prop="img">
							<el-upload action="http://127.0.0.1:8888/upload" list-type="picture-card"
								:on-success="addhandleAvatarSuccess" :on-preview="addhandlePictureCardPreview"
								:on-remove="addhandleRemove">
								<i class="el-icon-plus"></i>
							</el-upload>
							<!-- 放大图片效果对话框 -->
							<el-dialog :visible.sync="adddialogVisible">
								<img width="100%" :src="adddialogImageUrl" alt="">
							</el-dialog>
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button @click="addReset">取 消</el-button>
						<el-button type="primary" @click="addSumbit">确 定</el-button>
					</div>
				</el-dialog>
				<!-- 修改用户信息的对话框 -->
				<el-dialog title="修改用户" :visible.sync="updateUserdialogFormVisible" @close="updateReset"
					style="margin-top: -80px;">
					<el-form :model="updateUser" :rules="updateRule" ref="updateuserref">
						<el-form-item label="编号" :label-width="formLabelWidth" prop="id">
							<el-input v-model="updateUser.id" autocomplete="off" class="add" :disabled="true" size="small"></el-input>
						</el-form-item>
						<el-form-item label="账号" :label-width="formLabelWidth" prop="username">
							<el-input v-model="updateUser.username" autocomplete="off" class="add" size="small"></el-input>
						</el-form-item>
						<el-form-item label="密码" :label-width="formLabelWidth" prop="password">
							<el-input v-model="updateUser.password" autocomplete="off" class="add" size="small"></el-input>
						</el-form-item>
						<el-form-item label="真实姓名" :label-width="formLabelWidth" prop="name">
							<el-input v-model="updateUser.name" autocomplete="off" class="add" size="small"></el-input>
						</el-form-item>
						<el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
							<el-input v-model="updateUser.phone" autocomplete="off" class="add" @blur="selectUserByPhone"
								size="small"></el-input>
						</el-form-item>
						<el-form-item label="地址" :label-width="formLabelWidth" prop="address">
							<el-cascader v-model="updateUser.address" :options="cityData" class="add" size="small">
							</el-cascader>
						</el-form-item>
						<el-form-item label="头像" :label-width="formLabelWidth" prop="img">
							<el-upload action="http://127.0.0.1:8888/upload" list-type="picture-card"
								:on-success="addhandleAvatarSuccess" :on-preview="addhandlePictureCardPreview"
								:on-remove="addhandleRemove">
								<i class="el-icon-plus"></i>
							</el-upload>
							<!-- 放大图片效果对话框 -->
							<el-dialog :visible.sync="adddialogVisible">
								<img width="100%" :src="adddialogImageUrl" alt="">
							</el-dialog>
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button @click="addReset">取 消</el-button>
						<el-button type="primary" @click="addSumbit">确 定</el-button>
					</div>
				</el-dialog>
			</div>
		</el-card>
	</div>
</template>

<script>
	/* 引入省市县级联数据文件 */
	import cityData from '../assets/citydata.js'
	export default {
		data() {
			// 自定义密码验证规则
			var checkpassword = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入密码'));
				} else {
					// 定义正则表达式
					var reg = /^[a-zA-Z]\w{5,17}$/;
					if (!reg.test(value)) {
						callback(new Error('密码以字母开头，长度在6-18之间，只能包含字符、数字和下划线！'));
					}
					callback();
				}
			};
			// 自定义姓名验证规则
			var checkname = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入姓名'));
				} else {
					// 定义正则表达式
					var reg = /^([\u4e00-\u9fa5]{2,4})$/;
					if (!reg.test(value)) {
						callback(new Error('姓名为长度2-4之间的汉字！'));
					}
					callback();
				}
			};
			// 自定义手机号验证规则
			var checkphone = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入手机号'));
				} else {
					// 定义正则表达式
					var reg = /^\d{3,12}$/;
					if (!reg.test(value)) {
						callback(new Error('手机号长度在3-12之间！'));
					}
					callback();
				}
			};
			return {
				// 搜索的对象
				queryInfo: {
					name: '',
					phone: '',
					pageNum: 1,
					pageSize: 3,
					total: 0,
					starttime: '',
					endtime: '',
					createtime: ''
				},
				userList: [],
				addUserdialogTableVisible: false,
				addUserdialogFormVisible: false,
				addUser: {
					username: '',
					password: '',
					name: '',
					phone: '',
					img: '',
					address: '',
				},
				adddialogVisible: false, // 添加时的图片预览
				adddialogImageUrl: '', // 添加时的图片路径
				updateUserdialogTableVisible: false,
				updateUserdialogFormVisible: false,
				updateUser: {
					id: '',
					username: '',
					password: '',
					name: '',
					phone: '',
					img: '',
					address: '',
				},
				updatedialogVisible: false, // 添加时的图片预览
				updatedialogImageUrl: '', // 添加时的图片路径
				formLabelWidth: '150px',
				cityData: cityData,
				addRule: {
					username: [{
							required: true,
							message: '请输入账号',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 10,
							message: '长度在 2 到 10 个字符',
							trigger: 'blur'
						}
					],
					password: [{
						required: true,
						validator: checkpassword,
						trigger: 'blur'
					}],
					name: [{
						required: true,
						validator: checkname,
						trigger: 'blur'
					}],
					phone: [{
						required: true,
						validator: checkphone,
						trigger: 'blur'
					}],
					address: [{
						required: true,
						message: '请选择地址',
						trigger: 'blur'
					}]
				},
				updateRule: {
					username: [{
							required: true,
							message: '请输入账号',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 10,
							message: '长度在 2 到 10 个字符',
							trigger: 'blur'
						}
					],
					password: [{
						required: true,
						validator: checkpassword,
						trigger: 'blur'
					}],
					name: [{
						required: true,
						validator: checkname,
						trigger: 'blur'
					}],
					phone: [{
						required: true,
						validator: checkphone,
						trigger: 'blur'
					}],
					address: [{
						required: true,
						message: '请选择地址',
						trigger: 'blur'
					}]
				}
			};
		},
		mounted: function() { // 页面加载后默认执行的函数
			this.selectUsers();
		},
		methods: {
			// 分页查询所有的用户信息
			async selectUsers() {
				if(this.queryInfo.createtime.length==0){
					this.queryInfo.createtime = ['',''];
				}
				// 1.发送分页查询用户信息的请求
				let parms = new URLSearchParams();
				parms.append("pageNum", this.queryInfo.pageNum);
				parms.append("pageSize", this.queryInfo.pageSize);
				parms.append("name", this.queryInfo.name);
				parms.append("phone", this.queryInfo.phone);
				parms.append("starttime", this.queryInfo.createtime[0]);
				parms.append("endtime", this.queryInfo.createtime[1]);
				let res = await this.$http.post('selectUsers', parms);
				// 2.处理400的异常
				if (res.data.code == 400) {
					this.$message.error(res.data.msg);
					return;
				}
				// 3.处理200的正常情况
				if (res.data.code == 200) {
					// 获取数据
					this.userList = res.data.data.list;
					// 获取数据总条数
					this.queryInfo.total = res.data.data.total;
					this.queryInfo.starttime = '';
					this.queryInfo.endtime = '';
					this.queryInfo.createtime = ['',''];
				}
			},
			// 查询手机号是否唯一的函数
			async selectUserByPhone() {
				let res = await this.$http.get('selectUserByPhone?phone=' + this.addUser.phone);
				if (res.data.code == 200) {
					this.$message.error(res.data.msg);
					this.addUser.phone = '';
					return;
				}
			},
			// 重置搜索框的函数
			selectReset() {
				this.queryInfo.name = '';
				this.queryInfo.phone = '';
				this.queryInfo.createtime = ['',''];
			},
			// 每页显示条数发生改变触发的函数
			handleSizeChange(size) {
				this.queryInfo.pageSize = size;
				this.queryInfo.pageNum = 1;
				this.selectUsers();
			},
			// 当前页发生改变触发的函数
			handleCurrentChange(pn) {
				this.queryInfo.pageNum = pn;
				this.selectUsers();
			},
			handleAvatarSuccess(res, file) {
				this.imageUrl = URL.createObjectURL(file.raw);
			},
			// 添加用户的取消按钮
			addReset() {
				this.$refs['adduserref'].resetFields();
				this.addUserdialogFormVisible = false;
			},
			addSumbit() {
				this.$refs['adduserref'].validate(async (valid) => {
					// 收集数据
					if (valid) {
						let param = new URLSearchParams();
						param.append('username', this.addUser.username);
						param.append('password', this.addUser.password);
						param.append('name', this.addUser.name);
						param.append('phone', this.addUser.phone);
						param.append('img', this.addUser.img);
						param.append('address', this.addUser.address);
						// 发送请求
						let res = await this.$http.post('addUser', param);
						// 处理异常
						if (res.data.code == 400) {
							this.$message.error(res.data.msg);
							return;
						}
						// 添加成功
						if (res.data.code == 200) {
							this.$message.success(res.data.msg);
							// 重新查询
							this.selectUsers();
							// 关闭对话框
							this.addUserdialogFormVisible = false;
							// 图片路径关闭
							this.adddialogImageUrl = '';
							// 清空表单
							this.addUser.username = '';
							this.addUser.password = '';
							this.addUser.name = '';
							this.addUser.phone = '';
							this.addUser.img = '';
							this.addUser.address = '';
						}
					} else {
						console.log('error submit!!');
						this.$message.error('请检查数据！')
						return false;
					}
				});
			},
			// 图片预览的效果函数
			addhandlePictureCardPreview(file) {
				this.adddialogImageUrl = file.url;
				this.adddialogVisible = true;
			},
			// 图片上传的钩子函数
			addhandleAvatarSuccess(res, file) {
				this.adddialogImageUrl = URL.createObjectURL(file.raw);
				if (res.code == 200) {
					// 判断是否成功，如果成功，则把返回的图片名称赋值给addUser.img对象即可
					this.addUser.img = res.msg;
				}
			},
			// 图片移除的钩子函数
			addhandleRemove(file, fileList) {
				this.addUser.img = '';
				// console.log(file);
				// 如果是多张图片需要移除
				let tname = file.response.msg; // 需要移除的图片名称
				this.addUser.img.replace(tname, '');
			},
			// 根据编号修改查询
			async selectUserById(id) {
				// 先根据id来查询用户信息
				let res = await this.$http.get('selectUserById?id=' + id);
				// 查询失败处理
				if (res.data.code == 400) {
					this.$message.error(res.data.msg);
					return;
				}
				// 把用户信息预览在对话框中
				if (res.data.code == 200) {
					// 获取修改的用户信息
					this.edituser = res.data.data;
					let fl = {
						name: this.edituser.img,
						url: 'http://127.0.0.1:8888/showImg?filename=' + this.edituser.img
					};
					this.filelist.push(fl);
					// 打开修改的对话框
					this.editformdialogFormVisible = true;
				}
			},
			updateReset() {
				this.$refs['updateuserref'].resetFields();
				this.updateUserdialogFormVisible = false;
			},
			// 删除用户信息
			delUser(id) {
				this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					// 调用后端的删除接口
					let res = await this.$http.get('delUser?id=' + id);
					if (res.data.code == 200) {
						this.$message.success(res.data.msg);
					}
					if (res.data.code == 400) {
						this.$message.error(res.data.msg);
					}
					this.queryInfo.pageNum = 1;
					this.selectUsers();
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
		}
	}
</script>

<style scoped>
	.el-card {
		margin-top: 15px;
		text-align: left;
		padding: 20px;
	}

	.el-input {
		display: inline-block;
		width: 235px;
		margin-right: 50px;
	}

	.el-table {
		margin-top: 20px;
	}

	.b1 {
		float: right;
	}

	.add {
		width: 70%;
	}
</style>
